package com.oceansoft.xml.biz;

import java.io.FileNotFoundException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.oceansoft.xml.bean.Person;
import com.oceansoft.xml.util.NullValueException;

public class PersonTransitionImpl implements ITransition {

	public StringBuffer Object2XML(Object object) throws NullValueException {
		Person person = (Person) object;
		StringBuffer sb = new StringBuffer("<person ");
		if (person.getId().trim() == "" || null == person.getId()) {
			throw new NullValueException();
		}
		if (person.getOrgId().trim() == "" || null == person.getOrgId()) {
			throw new NullValueException();
		}
		String name = person.getName() == null
				|| person.getName().trim().equals("") ? "" : person.getName();
		String note = person.getNote() == null
				|| person.getNote().trim().equals("") ? "" : person.getNote();
		sb.append("id=\"" + person.getId() + "\" ").append(
				"name=\"" + name + "\" ").append(
				"orgId=\"" + person.getOrgId() + "\" ").append(
				"note=\"" + note + "\" ").append(" />");
		return sb;
	}

	public Person XML2Object(String xml) throws FileNotFoundException,
			DocumentException {
		Person person = new Person();
		Document doc = DocumentHelper.parseText(xml);
		Element personElm = (Element) doc.selectSingleNode("person");
		person.setId(personElm.attributeValue("id"));
		person.setName(personElm.attributeValue("name"));
		person.setOrgId(personElm.attributeValue("orgId"));
		person.setNote(personElm.attributeValue("note"));
		return person;
	}

}
